<template>
  <view class="chat-input">
    <!-- 悬浮输入框之上的快捷按钮 -->
    <view class="chat-input-toolbar" v-if="config.chatInputToolbar.show">
      <view v-for="(item, index) in toolbarList" :key="index" @tap="item.action" class="toolbar-item">
        {{ item.title }}
      </view>
    </view>

    <view class="input-toolbar">
      <view class="chatIcon icon-shengyin" style="font-size: 60rpx" @tap="switchInputMode"></view>

      <input
        v-if="!isVoiceMode"
        class="input-box"
        v-model="inputContent"
        type="text"
        border="none"
        placeholder="请输入消息"
        :maxlength="500"
        @confirm="sendTextMessage"
      />
      <!-- :disabled="!isConnected"
      :placeholder="isConnected ? '请输入消息' : '当前未连接客服'" -->

      <view v-else class="voice-button">
        <!-- 暂不支持语音 -->
        <recorderBtn @onEnd="(data) => handleFuncSelect({ type: 'voice', data })" />
      </view>

      <view
        class="chatIcon icon-biaoqing_xiao"
        :class="{ active: bottomType === 'emoji' }"
        style="font-size: 60rpx"
        @tap="changeBottomType('emoji')"
      ></view>
      <view
        class="chatIcon icon-shuliang-zengjia"
        :class="{ active: bottomType === 'more' }"
        style="font-size: 60rpx"
        @tap="changeBottomType('more')"
      ></view>
    </view>
    <view class="chat-bottom">
      <view class="chat-bottom-content" v-if="bottomType === 'emoji'">
        <view class="emoji-title" style="width: 100%" v-if="historyEmojis.length > 0">最近使用</view>
        <view style="display: flex; flex-wrap: wrap; justify-content: flex-start; width: 100%">
          <view
            v-for="(line, index) in historyEmojis"
            :key="index"
            class="emoji-item"
            :data-emoji="line"
            @tap="insertEmoji"
          >
            {{ line }}
          </view>
        </view>

        <view class="emoji-title" style="width: 100%">表情符号</view>
        <view v-for="(line, index) in emojis" :key="index" class="emoji-item" :data-emoji="line" @tap="insertEmoji">
          {{ line }}
        </view>
      </view>
      <view class="chat-bottom-content" v-else-if="bottomType === 'more'">
        <FuncGrid @select="handleFuncSelect" />
      </view>
      <view v-else-if="!isConnected">
        <slot name="no-service"></slot>
      </view>
    </view>
  </view>
  <u-modal
    :show="pageStatus.showModal"
    :title="pageStatus.title"
    :content="pageStatus.content"
    confirmColor="#ffb619"
    @close="pageStatus.showModal = false"
    @confirm="pageStatus.showModal = false"
  >
    <template #default>
      <text style="font-weight: bold; color: #ffb619">{{ pageStatus.content }}</text>
    </template>
  </u-modal>

  <popup-leaving-message v-model:show="pageStatus.showLeavingAMessage" />
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from "vue";
import popupLeavingMessage from "./popup-leaving-message.vue";
import recorderBtn from "./recorder-btn/recorder-btn.vue";
import FuncGrid from "./funcs/index.vue";
import libsEmojis from "../libs/emojis";
import config from "../config";
import store from "../utils/store";

const emits = defineEmits([
  "send-message",
  "send-image",
  "send-voice",
  "send-video",
  "send-online-service",
  "send-wecat-info",
  "debug",
]);

const pageStatus = reactive({
  showModal: false,
  showLeavingAMessage: false,
  title: "拨打客服热线",
  content: "暂无可拨打的客服热线",
});

// 当前是否已连接客服
const isConnected = ref(false);
// 输入框内容
const inputContent = ref("");
// 是否是语音模式
const isVoiceMode = ref(false);

// 快捷按钮
const toolbarList = ref([
  {
    title: "客服热线",
    action: () => {
      pageStatus.showModal = true;
    },
  },
  {
    title: "留言",
    action: () => {
      pageStatus.showLeavingAMessage = true;
    },
  },
]);

// 底部区域显示类型  emoji 表情 / more 更多
const bottomType = ref("");
// 表情
const emojis = ref(libsEmojis);
// 历史表情
const historyEmojis = ref(store.getHistoryEmojis());

const changeBottomType = (type) => {
  // 其他按钮点击时，强制变为输入状态
  isVoiceMode.value = false;

  if (bottomType.value == type) {
    bottomType.value = "";
    // TODO 并且让输入框 获取焦点
  } else {
    bottomType.value = type;
  }
};

// 插入表情
const insertEmoji = (e) => {
  // if (!isConnected.value) return;
  console.log("insertEmoji:", e.target.dataset.emoji);
  inputContent.value += e.target.dataset.emoji;
  store.saveHistoryEmojis(e.target.dataset.emoji);
  nextTick(() => {
    historyEmojis.value = store.getHistoryEmojis();
  });
};

// const recorderManager = uni.getRecorderManager();

// 切换输入模式
const switchInputMode = () => {
  isVoiceMode.value = !isVoiceMode.value;
};

// 发送文本消息
const sendTextMessage = () => {
  if (inputContent.value === "#debug#") {
    return uni.navigateTo({
      url: "/pages/subSetting/debug/debug",
    });
  }
  if (!inputContent.value || !inputContent.value.trim()) return;
  emits("send-message", inputContent.value);
  inputContent.value = "";
};

// 处理功能选择
const handleFuncSelect = (playload) => {
  // if (/* !isConnected.value &&  */playload.type !== "debug") return uni.showToast({ title: "当前未连接客服", icon: "none" });
  console.log(playload);
  switch (playload.type) {
    case "richText-image":
      // TODO 得先自己上传, 交互体验不太好
      emits("send-message", inputContent.value);
      break;
    case "image":
      emits("send-image", {
        path: playload.data,
        type: playload.type,
      });
      break;
    case "video":
      emits("send-video", {
        path: playload.data,
        url: playload.data,
        type: playload.type,
      });
      break;
    case "voice":
      emits("send-voice", {
        ...playload.data,
        type: playload.type,
      });
      break;
    case "voice-btn-show":
      isVoiceMode.value = true;
      break;
    // 处理其他类型...
    case "wecat-info":
      emits("send-wecat-info", playload);
      break;
    // 调试/测试
    case "debug":
      emits("debug", playload);
      break;
  }
  // 选择后关闭面板
  bottomType.value = "";
};

const version = ref("");

onMounted(() => {
  uni.$on("KN-IM:connect-status", (status) => {
    if (status === "connected") {
      isConnected.value = true;
    } else {
      isConnected.value = false;
    }
  });

  uni.getSystemInfo({
    success: (result) => {
      version.value = result.appVersion;
    },
    fail: (error) => {},
  });

});

onUnmounted(() => {
  uni.$off("KN-IM:connect-status");
});
</script>

<style scoped lang="scss">
$theme-color: #ffc549;
$theme-color-light: #fff8e8;

.chat-input {
  position: relative;
  padding: 20rpx;
}

.chat-input-toolbar {
  position: absolute;
  top: -80rpx;
  left: 0;
  right: 0;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 20rpx;
  padding: 10rpx;
  overflow-x: auto;

  .toolbar-item {
    font-size: 25rpx;
    padding: 10rpx 20rpx;
    background-color: #f5f5f5;
    border-radius: 999rpx;
    background-color: $theme-color-light;
    border: 1px solid $theme-color;
    color: $theme-color;
    font-weight: 600;
    min-width: 100rpx;
    text-align: center;
  }
}

.input-toolbar {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.input-box {
  flex: 1;
  padding: 0 20rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 10rpx 20rpx;
  height: 50rpx;
  font-size: 30rpx;
}

.voice-button {
  flex: 1;
  text-align: center;
  background-color: #f5f5f5;
  padding: 10rpx;
  border-radius: 8rpx;
  color: #b9b9b9;
}

.chat-bottom {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20rpx;
  color: $theme-color;
  transition: all 0.5s;

  .chat-bottom-content {
    display: flex;
    flex-wrap: wrap;
    max-height: 400rpx;
    overflow-y: auto;
    align-items: center;
    width: 90%;
    justify-content: flex-start;
    transition: all 0.5s;

    .emoji-title {
      font-family: Arial, Helvetica, sans-serif;
      font-size: 25rpx;
      color: #999;
    }

    .version {
      font-size: 20rpx;
      color: #999;
      margin-top: 10rpx;
      width: 100%;
      text-align: center;
    }

    .emoji-item {
      font-size: 40rpx;
      line-height: 70rpx;
      padding: 10rpx;
    }

    .chat-bottom-title {
      font-size: 28rpx;
      text-align: center;
      margin-top: 10rpx;
    }
  }
}

.chatIcon {
  &.active {
    color: $theme-color;
  }
}
</style>
